<template>
  <div class="exam-wrap">
    <!-- 面包屑导航 -->
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-fa fa-eye"></i> 考试查询
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 输入框和按钮 -->
    <div class="search-bar">
      <el-input
        v-model="studentId"
        placeholder="输入学生ID"
        class="input-id"
      ></el-input>
      <el-button type="primary" @click="getList">获取考试信息</el-button>
    </div>

    <!-- 数据表格 -->
    <div class="container">
      <div v-if="loading" class="loading">
        <el-spinner type="dots"></el-spinner> <!-- Loading spinner -->
        加载中...
      </div>
      <div v-else class="table">
        <el-table :data="tableData" stripe>
          <el-table-column label="选课Id" prop="studentCourseId" />
          <el-table-column label="课程名" prop="courseName" />
          <el-table-column label="教师" prop="teacherName" />
          <el-table-column label="考试日期" prop="examDate" />
          <el-table-column label="考试地点" prop="examLocation" />
        </el-table>
      </div>
    </div>

    <!-- 错误信息 -->
    <div v-if="error" class="error-message">
      <el-alert
        title="加载失败"
        type="error"
        description="获取考试信息失败，请稍后重试。"
        show-icon
        center
      />
    </div>
  </div>
</template>

<script>
import axios from 'axios'; // 直接在组件中导入 axios

export default {
  name: "StudentExam",
  data() {
    return {
      studentId: "", // 存储用户输入的学生ID
      tableData: [], // 存储表格数据
      loading: false, // 加载状态
      error: false   // 错误状态
    };
  },
  methods: {
    // 获取考试数据列表
    getList() {
      // 输入学生 ID 为空时，显示提示
      if (!this.studentId) {
        this.$message.error("请输入学生ID");
        return;
      }

      this.loading = true;
      this.error = false;

      // 直接使用 axios 发送请求到后端
      axios.get('http://localhost:8085/student/exam/list', {
        params: { studentId: this.studentId }  // 传递 studentId 参数
      })
      .then(res => {
        if (res.status === 200 && res.data.length > 0) {
          this.tableData = res.data;  // 正确返回考试数据
        } else {
          this.tableData = [];
          this.error = true;
          this.$message.error("未能获取到考试数据");
        }
      })
      .catch(() => {
        this.error = true;  // 处理请求错误
        this.$message.error("获取考试信息失败，请稍后再试");
      })
      .finally(() => {
        this.loading = false; // 取消加载状态
      });
    }
  }
};
</script>

<style scoped>
.exam-wrap {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.error-message {
  margin-top: 20px;
}

.table {
  margin-top: 20px;
}
</style>
